import request from '../utils/request.js'

async function register(btn) {

    const usernameInput = document.getElementById('username')
    const passwordInput = document.getElementById('password')
    
    const username = usernameInput.value
    const password = passwordInput.value
    
    if (username.trim() === '' || password.trim() === '') {
        showToast('用户名或密码不能为空！', 'error')
        return
    }

    btn.classList.add('loading')
    btn.disabled = true
    
    const config = {
        method: 'post',
        url: '/user/register',
        data: {
            userName: username,
            permission:'normal',
            userPassword:password,
        }
    }

    try {
        const response = await request(config)
        // localStorage.setItem('isLoggedIn', 'true')
        // localStorage.setItem('isAdmin', 'false')
        // localStorage.setItem('currentUser', username)
        

        showToast('注册成功！', 'success')
        
        setTimeout(() => {
            window.location.href = 'login.html'
        },1000)
        
        
    } catch (error) {
        //console.log(JSON.stringify(error))
        showToast(`${error.msg}`, 'error')

    } finally {
        btn.classList.remove('loading')
        btn.disabled=false
    }
    
}

window.register=register